var map = new BMap.Map("deviceMapContent");  // 创建Map实例
var point = new BMap.Point(119.014521, 25.459865);// 初始化地图,用城市名设置地图中心点
map.centerAndZoom(point, 14);//
map.enableScrollWheelZoom();//地图可以缩放
map.enableContinuousZoom();
var blist = [];
var districtLoading = 0;
function getBoundary() {
    addDistrict("莆田市");

}
/**
 * 添加行政区划
 * @param {} districtName 行政区划名
 * @returns  无返回值
 */
function addDistrict(districtName) {
    //使用计数器来控制加载过程
    districtLoading++;
    var bdary = new BMap.Boundary();
    bdary.get(districtName, function (rs) {       //获取行政区域
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
            alert('未能获取当前输入行政区域');
            return;
        }
        for (var i = 0; i < count; i++) {
            blist.push({ points: rs.boundaries[i], name: districtName });
        };
        //加载完成区域点后计数器-1
        districtLoading--;
        if (districtLoading == 0) {
            //全加载完成后画端点
            drawBoundary();
        }
    });
}

function drawBoundary() {
    //包含所有区域的点数组
    var pointArray = [];
    var pNW = { lat: 59.0, lng: 73.0 };
    var pNE = { lat: 59.0, lng: 136.0 };
    var pSE = { lat: 3.0, lng: 136.0 };
    var pSW = { lat: 3.0, lng: 73.0 };
    var pArray = [];
    pArray.push(pNW);
    pArray.push(pSW);
    pArray.push(pSE);
    pArray.push(pNE);
    pArray.push(pNW);
    //循环添加各闭合区域
    for (var i = 0; i < blist.length; i++) {
        //添加显示用标签层
        var label = new BMap.Label(blist[i].name, { offset: new BMap.Size(20, -10) });
        label.hide();
        map.addOverlay(label);

        //添加多边形层并显示
        var ply = new BMap.Polygon(blist[i].points, { strokeWeight: 1, strokeColor: "#FF0000", fillOpacity: 0.01, fillColor: " #FFFFFF" }); //建立多边形覆盖物
        ply.name = blist[i].name;
        ply.label = label;
        map.addOverlay(ply);


        //将点增加到视野范围内
        var path = ply.getPath();
        pointArray = pointArray.concat(path);
        //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
        pArray = pArray.concat(path);
        pArray.push(pArray[0]);
    }


    //添加遮蔽层
    var plyall = new BMap.Polygon(pArray, { strokeOpacity: 0.0000001, strokeColor: "#000000", strokeWeight: 0.00001, fillColor: "#000000", fillOpacity: 0.6 }); //建立多边形覆盖物
    map.addOverlay(plyall);
}
getBoundary();
var deviceId = getQueryString('deviceId');
$("#addMap").click(function () {
    drawingManager.open();
    drawingManager.setDrawingMode(BMAP_DRAWING_MARKER);
});
var overlays = [];
//实例化鼠标绘制工具
var overlaycomplete = function (e) {
    overlays.push(e.overlay);
    drawingManager.close();
};
//实例化鼠标绘制工具
var styleOptions = {
    strokeColor: "blue",    //边线颜色。
    fillColor: "#0081cc",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 2,       //边线的宽度，以像素为单位。
    //strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
};
var drawingManager = new BMapLib.DrawingManager(map, {
    isOpen: false, //是否开启绘制模式
    enableDrawingTool: false, //是否显示工具栏
    drawingToolOptions: {
        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
        offset: new BMap.Size(5, 5), //偏离值
        drawingTypes: [
            BMAP_DRAWING_MARKER,
            BMAP_DRAWING_POLYLINE
        ]
    },
    circleOptions: styleOptions, //圆的样式
    polylineOptions: styleOptions //线的样式
});
drawingManager.addEventListener('overlaycomplete', overlaycomplete);
//绘制点成功后事件
drawingManager.addEventListener("markercomplete", function (e, overlay) {
    addForm(overlay);
});
/**查询全部的流量传感器 **/
    $.ajax({
        type: "GET",
        url: "/rest/web/dtu/selectDtuList",
        dataType: "json",
        success: function (data) {
            var dtuList = data.data,
                dtuHtml="";
            $.each(dtuList, function (i, o) {
                dtuHtml+='<option value="'+o.dtuId+'">'+o.code+'</option>'
            });
            $("select[name='dtuId']").html(dtuHtml);
            return queryDevDetail(deviceId);
        }
    });

/**查询流量传感器详情页面 **/
function queryDevDetail(deviceId){
    $.ajax({
        type: "GET",
        url: "/rest/web/device/selectDeviceDetail",
        data:{
            deviceId:deviceId
        },
        dataType: "json",
        success: function (data) {
            //使用bui渲染表单的详情方法
            var form = $("#editForm")[0];
            BUI.FormHelper.setFields(form, data.data);
            data.data.lng==''||data.data.lng==null?$(".anchorTR").show():setSensePoint(data.data)

        }
    });
}

/**
 * 绘制点设备传感的点
 */
function addForm(overlay) {
    var sContent = "<div class='edit-sense' style='width:330px;'><form>" +
        "<div class='modal-header'>新增传感设备经纬度</h4> </div>" +
        "<div class='modal-body'>" +
        "<div class='input-group'><label><span>地址:</span></label><input class='form-control' type='text' name='address'  style='width: 260px;'/></div>" +
        "<div class='classify-input input-group'><label><span>经度:</span></label><input class='form-control' type='text' value='" + overlay.point.lng + "' name='lng' style='width: 96px;'  /><label><span>纬度:</span>" +
        "</label><input class='form-control' type='text' value='" + overlay.point.lat + "'  name='lat'  style='width: 86px;'/></div></div>" +
        "<div class='modal-footer'><a class='btn ensure-btn' onclick='saveBtn()'>确定</a>" +
        "</div>" +
        "</form></div>";
    var infoWindow = new BMap.InfoWindow(sContent);
    overlay.openInfoWindow(infoWindow);
    overlay.addEventListener("click", function () {
        this.openInfoWindow(infoWindow);
    });
    //弹出窗口被关闭掉触发删除新建点
    infoWindow.addEventListener("close", function () {
        map.removeOverlay(overlay);
    });
    $(document).on('click','#addBtn',function(){
        alert("regj")
    })
}


/**
 * 绘制传感设备点
 * @param obj
 */
var marker1='';
function setSensePoint(dtuList) {
    var senseContent = "";
    senseContent = senseContent + "<div class='edit-sense' id='senseDemo'  style='width:330px;'><form>" +
        "<div class='modal-header'>传感设备</h4> </div>" +
        "<div class='modal-body'>" +
        "<div class='input-group'><label><span>地址:</span></label><input class='form-control' type='text' name='address'  value='" + dtuList.address + "'  style='width: 260px;'/></div>" +
        "<div class='classify-input input-group'><label><span>经度:</span></label><input class='form-control editLng' type='text' value='" + dtuList.lng + "' name='lng' style='width: 96px;'/><label><span>纬度:</span>" +
        "</label><input class='form-control editLat' type='text' value='" + dtuList.lat + "'  name='lat' style='width: 86px;' /></div>" +
        "</div>" +
        " <div class='modal-footer'><a class='btn ensure-btn openBtn' onclick='iBtn()'>移动</a><a class='btn ensure-btn' onclick='saveBtn()'>确定</a>"+
        "</div></form></div>";
    var senseWindow = new BMap.InfoWindow(senseContent); // 创建信息窗口对象
    //创建传感小图标
    var pt = new BMap.Point(dtuList.lng, dtuList.lat);
    var myIcon;
    if(dtuList.isSysAlarmOn==1){
        if(dtuList.curFlow<dtuList.alarmThresholdLowerLimit || dtuList.curFlow>dtuList.alarmThresholdUpperLimit){
            myIcon = new BMap.Icon("/static/images/map_dtu1.png", new BMap.Size(22, 22));
        }else{
            myIcon = new BMap.Icon("/static/images/map_dtu.png", new BMap.Size(22, 22));
        }
    }else{
        myIcon = new BMap.Icon("/static/images/map_dtu.png", new BMap.Size(22, 22));
    }
    marker1 = new BMap.Marker(pt, {icon: myIcon}); // 创建标注
    map.addOverlay(marker1);
        marker1.openInfoWindow(senseWindow);

}
/**
 * 点击移动时进行拖拽，点击完成就阻止拖拽
 */
var y=1;
function iBtn(){
    if(y==1){
        $(".openBtn").text("完成");
        marker1.enableDragging();
        marker1.addEventListener("dragend", function(e){
            $(".editLng").val(e.point.lng);
            $(".editLat").val(e.point.lat);
        });
        y=2;
    }else{
        $(".openBtn").text("移动");
        marker1.disableDragging();
        y=1;
    }
}
/**
 * 点击弹出框确定按钮
 */
function saveBtn() {
    var dtuId= $('select[name="dtuId"]').val(),
        code= $('input[name="code"]').val(),
        name=$('input[name="name"]').val(),
        addrCode= $('input[name="addrCode"]').val(),
        price = $('input[name="price"]').val(),
        factor=$('input[name="factor"]').val(),
        protocolType=$('select[name="protocolType"]').val(),
        remark=$('textarea[name="remark"]').val(),
        address=$('input[name="address"]').val(),
        spec=$('input[name="spec"]').val(),
        age=$('input[name="age"]').val(),
        year=$('input[name="year"]').val(),
        personLiable=$('input[name="personLiable"]').val(),
        department=$('input[name="department"]').val(),
        lng=$('input[name="lng').val(),
        lat=$('input[name="lat').val();
        var data = {dtuId: dtuId,deviceId:deviceId, code: code, addrCode: addrCode, price: price,factor:factor,protocolType:protocolType,remark :remark ,lng:lng,lat:lat,name:name,address:address,spec:spec,age:age,year:year,personLiable:personLiable,department:department};
        saveDevice(data);
}
/**
 * 编辑传感设备
 * @param data
 */
function  saveDevice(data) {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: "/rest/web/device/updateDevice",
        data: data,
        success: function () {
            window.location.href = "/rest/web/device/toDeviceList";
        }
    })
}
